//
//  ReadingVC.m
//  qqqqqq
//
//  Created by iOSer on 2017/1/19.
//  Copyright © 2017年 iOSer. All rights reserved.
//

#import "ReadingVC.h"
#import <WebKit/WebKit.h>
@interface ReadingVC ()<UIWebViewDelegate,WKUIDelegate,WKNavigationDelegate>
@property(nonatomic,strong) UIView *tabBar;
@property(nonatomic,strong) UIButton *tabItem1;
@property(nonatomic,strong) UIButton *tabItem2;
@property(nonatomic,strong) UIButton *tabItem3;
@property(nonatomic,strong) UIView *topView;
@property(nonatomic,strong) UITextField *urlTextFiled;
@property(nonatomic,strong) UIButton *goBtn;
@property(nonatomic,strong) WKWebView *webView;

@property(nonatomic,strong) UIView *toolView;
@property(nonatomic,strong) UILabel *hostLab;
@property(nonatomic,strong) UIButton *disposeBtn;
@property(nonatomic,strong) UIButton *hintBtn;

@property(nonatomic,copy) NSString *RequesURLCopyStr;
@property(nonatomic,copy) NSString *hostCopyStr;
@end

@implementation ReadingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
//    NSString *path = @"http://www.baidu.com?iframe_hijack_redirected=1";
//    NSURL *url = [[NSURL alloc] initWithString:path];
    if ([self.loadurl rangeOfString:@"baidu"].location == NSNotFound) {
        
        if ([self.loadurl rangeOfString:@"?iframe_hijack_redirected=1"].location==NSNotFound) {
            self.loadurl =[NSString stringWithFormat:@"%@?iframe_hijack_redirected=1",self.loadurl];
        }
    }
    
    NSLog(@"%@",self.loadurl);
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.loadurl]]];
    [self.view addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ViewTaped)]];
    
    
}


- (void)ViewTaped{
    [self.view endEditing:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
-(void)viewWillDisappear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}



-(void)setupUI{
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tabBar];
    [self.tabBar addSubview:self.tabItem1];
    [self.tabBar addSubview:self.tabItem2];
    [self.tabBar addSubview:self.tabItem3];
    [self.topView addSubview:self.urlTextFiled];
    [self.topView addSubview:self.goBtn];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.toolView];
    [self.toolView addSubview:self.hostLab];
    [self.toolView addSubview:self.disposeBtn];
    [self.toolView addSubview:self.hintBtn];
    [_topView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@(64));
    }];
    [_tabBar makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.right.left.equalTo(self.view);
        make.height.equalTo(49);
    }];
    [_tabItem1 makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tabBar);
        make.left.equalTo(_tabBar);
        make.bottom.equalTo(_tabBar);
        make.width.equalTo(@(SCREEN_WIDTH/3));
    }];
    [_tabItem2 makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tabBar);
        make.left.equalTo(_tabItem1.mas_right);
        make.bottom.equalTo(_tabBar);
        make.width.equalTo(@(SCREEN_WIDTH/3));
    }];
    [_tabItem3 makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tabBar);
        make.left.equalTo(_tabItem2.mas_right);
        make.bottom.equalTo(_tabBar);
        make.width.equalTo(@(SCREEN_WIDTH/3));
    }];
    [_urlTextFiled makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView).offset(22+GGRealValue(5));
        make.left.equalTo(self.topView).offset(GGRealValue(20));
        make.bottom.equalTo(self.topView).offset(-GGRealValue(5));
        make.right.equalTo(self.topView).offset(-GGRealValue(80));
    }];
    [_goBtn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView).offset(22+GGRealValue(5));
        make.right.bottom.equalTo(self.topView).offset(-GGRealValue(5));
        make.left.equalTo(_urlTextFiled.mas_right).offset(20);
    }];
    [_webView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.tabBar.mas_top);
    }];
    [_toolView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_tabBar.mas_top);
        make.right.equalTo(self.view.mas_left).offset(GGRealValue(20));
        make.height.equalTo((GGRealValue(40)));
        make.width.equalTo(@(GGRealValue(250)));
    }];
    [_hostLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_toolView);
        make.left.equalTo(_toolView).offset(GGRealValue(5));
        make.width.equalTo(@(GGRealValue(150)));
    }];
    
    [_hintBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_toolView);
        make.size.equalTo(CGSizeMake(GGRealValue(20), GGRealValue(40)));
        make.bottom.equalTo(_toolView);
    }];
    
    [_disposeBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_hintBtn.mas_left);
        make.top.bottom.equalTo(_toolView);
        make.left.equalTo(_hostLab.mas_right).offset(GGRealValue(20));
    }];
}

#pragma mark - webView代理
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}


-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [[GGShowHUDTool sharedInstance] dismiss];
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
//                NSLog(@"%@", result);
    }];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    
    NSString *willRequestUrl = [navigationAction.request.URL absoluteString];
    
    NSLog(@"---%@",willRequestUrl);
    self.RequesURLCopyStr = willRequestUrl;
    
//    if ([self.loadurl rangeOfString:@"baidu"].location == NSNotFound) {
    
//        if ([self.loadurl rangeOfString:@"?iframe_hijack_redirected=1"].location==NSNotFound) {
//            self.loadurl =[NSString stringWithFormat:@"%@?iframe_hijack_redirected=1",self.loadurl];
//            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.loadurl]]];
//            decisionHandler(WKNavigationActionPolicyAllow);
//            return;
//
//        }
    
    if (self.hostCopyStr) {
//        NSURL *url = [NSURL URLWithString:willRequestUrl];
        NSString *host = [navigationAction.request.URL host]?[navigationAction.request.URL host]:@"";
        if (![host isEqualToString:self.hostCopyStr] && ![willRequestUrl isEqualToString:@"about:blank"]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
  
//    [[GGShowHUDTool sharedInstance] showGetHud:@"加载中..."];
    self.urlTextFiled.text = willRequestUrl;
        //    }
    
//    if (![willRequestUrl isEqualToString:self.loadurl]) {
//        
//        
        decisionHandler(WKNavigationActionPolicyAllow);
//        return;
//    }
    
    
    
    
//    ReadingVC *showWeb = [[ReadingVC alloc] init];
//    showWeb.loadurl = willRequestUrl;
//    [webView loadRequest:]
//    [self.navigationController pushViewController:showWeb animated:YES];
    
    
    
    // 不允许跳转
    
    
    //    NSString *aaa = [navigationAction.request]
    //    decisionHandler(WKNavigationActionPolicyAllow);
    
}
-(void)tabItemClick:(UIButton *)button{
    NSLog(@"%ld",(long)button.tag);
    if (button.tag == 3) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.RequesURLCopyStr]]];
    }
}
-(void)disposeBtnClick:(UIButton *)button{
    button.selected = !button.selected;
    
    if (button.selected == YES) {
        
        NSURL *url = [NSURL URLWithString:self.RequesURLCopyStr];
        self.hostCopyStr = [url host];
    }else{
        
        self.hostCopyStr = nil;
    }
    self.hostLab.text = self.hostCopyStr;

}
-(void)goBtnClick{
    if (self.urlTextFiled.text.length!=0) {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@",self.urlTextFiled.text];
        loadStr = [loadStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        loadStr = [loadStr lowercaseString];
         [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:loadStr]]];
        [self.view endEditing:YES];
    }
    
}
-(void)hintBtnClick{
    self.hintBtn.selected = !self.hintBtn.selected;
    [UIView animateWithDuration:0.3 animations:^{
        
        if (self.hintBtn.selected == YES) {
            [self.toolView remakeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(_tabBar.mas_top);
                make.left.equalTo(self.view);
                make.height.equalTo((GGRealValue(40)));
                make.width.equalTo(@(GGRealValue(250)));
            }];
            [self.toolView.superview layoutIfNeeded];
            [self.toolView.layer removeAllAnimations];
            CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
            colorAnimation.duration = 0.3;
            colorAnimation.repeatCount = 1;
            colorAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
            colorAnimation.fromValue =  [NSNumber numberWithDouble:0.3f];
            colorAnimation.toValue = [NSNumber numberWithDouble:1.0f];
            colorAnimation.fillMode = kCAFillModeForwards;
            colorAnimation.removedOnCompletion = NO;
            [self.toolView.layer addAnimation:colorAnimation forKey:@"opacityOpenAnimation"];
            
            self.hintBtn.imageView.transform = CGAffineTransformMakeRotation(M_PI+0.00000001);
        }else{
            [self.toolView remakeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(_tabBar.mas_top);
                make.right.equalTo(self.view.mas_left).offset(GGRealValue(20));
                make.height.equalTo((GGRealValue(40)));
                make.width.equalTo(@(GGRealValue(250)));
            }];
            [self.toolView.superview layoutIfNeeded];
            [self.toolView.layer removeAllAnimations];
            CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
            colorAnimation.duration = 0.3;
            colorAnimation.repeatCount = 1;
            colorAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
            colorAnimation.fromValue =  [NSNumber numberWithDouble:1.0f];
            colorAnimation.toValue = [NSNumber numberWithDouble:0.3f];
            colorAnimation.fillMode = kCAFillModeForwards;
            colorAnimation.removedOnCompletion = NO;
            [self.toolView.layer addAnimation:colorAnimation forKey:@"opacityOpenAnimation"];
            self.hintBtn.imageView.transform = CGAffineTransformIdentity;
        }
        
    } completion:^(BOOL finished) {
        
    }];
}
#pragma mark - 懒加载
-(UIView *)tabBar{
    if (!_tabBar) {
        _tabBar = [UIView new];
        [_tabBar setBackgroundColor:HEXColor(0x000000, 1)];
    }
    return _tabBar;
}

-(UIButton *)tabItem1{
    if (!_tabItem1) {
        _tabItem1 = [UIButton new];
        _tabItem1.tag = 1;
        [_tabItem1 setBackgroundColor:HEXColor(0x000000, 1)];
        [_tabItem1 setImage:setIMG(@"webBackicon") forState:UIControlStateNormal];
        [_tabItem1 setTitle:@"" forState:UIControlStateNormal];
        [_tabItem1 addTarget:self action:@selector(tabItemClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tabItem1;
}

-(UIButton *)tabItem2{
    if (!_tabItem2) {
        _tabItem2 = [UIButton new];
        _tabItem2.tag = 2;
        [_tabItem2 setBackgroundColor:HEXColor(0x000000, 1)];
        [_tabItem2 setImage:setIMG(@"webgotoicon") forState:UIControlStateNormal];
        [_tabItem2 setTitle:@"" forState:UIControlStateNormal];
        [_tabItem2 addTarget:self action:@selector(tabItemClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tabItem2;
}

-(UIButton *)tabItem3{
    if (!_tabItem3) {
        _tabItem3 = [UIButton new];
        _tabItem3.tag = 3;
        [_tabItem3 setBackgroundColor:HEXColor(0x000000, 1)];
        [_tabItem3 setImage:setIMG(@"webRefreshicon") forState:UIControlStateNormal];
        [_tabItem3 setTitle:@"" forState:UIControlStateNormal];
        [_tabItem3 addTarget:self action:@selector(tabItemClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tabItem3;
}



-(UIView *)topView{
    if (!_topView) {
        _topView = [UIView new];
        [_topView setBackgroundColor:HEXColor(0x000000, 1)];
    }
    return _topView;
}

-(UITextField *)urlTextFiled{
    if (!_urlTextFiled) {
        _urlTextFiled = [UITextField new];
        _urlTextFiled.borderStyle = UITextBorderStyleRoundedRect;
        _urlTextFiled.backgroundColor = [UIColor whiteColor];
        _urlTextFiled.textColor = HEXColor(0x000000, 1);
        _urlTextFiled.keyboardType = UIKeyboardTypeURL;
        _urlTextFiled.clearButtonMode = UITextFieldViewModeAlways;
        _urlTextFiled.tintColor = HEXColor(0x000000, 1);
        _urlTextFiled.font = [UIFont systemFontOfSize:GGRealValue(16)];
    }
    
    return _urlTextFiled;
}

-(UIButton *)goBtn{
    if (!_goBtn) {
        _goBtn = [UIButton new];
        [_goBtn setBackgroundColor:HEXColor(0x000000, 1)];
        [_goBtn setTitle:@"前往" forState:UIControlStateNormal];
        [_goBtn setTitleColor:HEXColor(0xffffff, 1) forState:UIControlStateNormal];
        [_goBtn addTarget:self action:@selector(goBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _goBtn;
}


-(WKWebView *)webView{
    if (!_webView) {
        _webView = [WKWebView new];
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        
    }
    return _webView;
}
-(UIView *)toolView{
    if (!_toolView) {
        _toolView = [UIView new];
        [_toolView setBackgroundColor:HEXColor(0x000000, 1)];
        _toolView.layer.opacity = 0.3;
    }
    return _toolView;
}

-(UILabel *)hostLab{
    if (!_hostLab) {
        _hostLab = [UILabel new];
        _hostLab.textColor = HEXColor(0xffffff, 1);
        _hostLab.font = [UIFont systemFontOfSize:GGRealValue(13)];
    }
    return _hostLab;
}

-(UIButton *)disposeBtn{
    if (!_disposeBtn) {
        _disposeBtn = [UIButton new];
        [_disposeBtn setBackgroundColor:HEXColor(0x000000, 1)];
        [_disposeBtn setTitle:@"去广告" forState:UIControlStateNormal];
        _disposeBtn.titleLabel.font = [UIFont systemFontOfSize:GGRealValue(13)];
        [_disposeBtn setTitleColor:HEXColor(0xffffff, 1) forState:UIControlStateNormal];
        [_disposeBtn setTitleColor:HEXColor(0x0bd986, 1) forState:UIControlStateSelected];
        [_disposeBtn addTarget:self action:@selector(disposeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _disposeBtn;
}

-(UIButton *)hintBtn{
    if (!_hintBtn) {
        _hintBtn = [UIButton new];
        [_hintBtn setBackgroundColor:HEXColor(0x000000, 1)];
        [_hintBtn setImage:setIMG(@"webHintImgicon") forState:UIControlStateNormal];
        [_hintBtn addTarget:self action:@selector(hintBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _hintBtn;
}

@end
